package org.example.c2;

import lombok.extern.slf4j.Slf4j;

/**
 * @author liu-rui
 * @date 2020/6/1 上午11:15
 * @description 实践:ThreadLocal
 * 10个线程，每个线程统计1000累加值并打印
 * @since
 */
@Slf4j
public class Demo3 {
    /**
     * 线程安全的累加器
     */
    static class Adder {
        private ThreadLocal<Integer> sum = ThreadLocal.withInitial(() -> 0);

        public void add(int num) {
            sum.set(sum.get() + num);
        }

        public int get() {
            return sum.get();
        }
    }

    public static void main(String[] args) {
        Adder adder = new Adder();

        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                for (int j = 0; j < 1000; j++) {
                    adder.add(1);
                }

                log.info("{}", adder.get());
            }, "t" + i).start();
        }
    }
}
